#nullable enable

using Application.Core.Dto;
using Application.Core.Entity;
using Application.Service.LogCache;
using Application.Service.Permissions;
using Application.Service.Users;
using Application.Web.Core.Services;

using BootstrapBlazor.Components;

using Furion.Logging;

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Microsoft.Extensions.Options;

using SqlSugar;

using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace Application.Web.Entry.Pages
{
    public partial class Users : ComponentBase
    {
        [Inject] public IUserService UserService { get; set; } = default!;
        [Inject] public CheckPermission checkPermissionService { get; set; } = default!;
        [Inject] public IJSRuntime JSRuntime { get; set; } = default!;
		[Inject] public NavigationManager Navigation { get; set; } = default!;

		[NotNull]
		private List<User>? Items { get; set; }

		[NotNull]
		private IEnumerable<User>? EditItems { get; set; }

        private bool _hasPermission = false;
        private bool _canAdd = false;
        private bool _canEdit = false;
        private bool _canDelete = false;
        private bool _isReadOnly = false;

		private readonly ConcurrentDictionary<User, IEnumerable<SelectedItem>> _cache = new();
		private static IEnumerable<int> PageItemsSource => new[] { 10, 20, 40 };

        protected override async Task OnInitializedAsync()
        {
            LogWrapper.Information("访问用户管理页面");
            
            // 检查页面访问权限
            _hasPermission = await checkPermissionService.CanAccessPageAsync("user");
            
            if (!_hasPermission)
            {
				checkPermissionService.RedirectToNoPermission();
                return;
            }

            // 检查是否为只读权限
            _isReadOnly = await checkPermissionService.IsPageReadOnlyAsync("user");

            // 检查操作权限
            _canAdd = await checkPermissionService.CanPerformOperationAsync("user.create");
            _canEdit = await checkPermissionService.CanPerformOperationAsync("user.modify");
            _canDelete = await checkPermissionService.CanPerformOperationAsync("user.delete");

            await base.OnInitializedAsync();
		}

        private void GoToHome()
        {
            Navigation.NavigateTo("/");
        }

		/// <summary>
		/// 查询操作方法
		/// </summary>
		/// <param name="options"></param>
		/// <returns></returns>
		private async Task<QueryData<User>> OnQueryAsync(QueryPageOptions options)
		{
			if (Items == null || Items.Count == 0)
			{
                Items = (await UserService.GetAllEntiyAsync()).ToList();
			}
            EditItems = Items;
			var items = Items.Where(options.ToFilterFunc<User>());
			// 排序
			var isSorted = false;
			if (!string.IsNullOrEmpty(options.SortName))
			{
				items = items.Sort(options.SortName, options.SortOrder);
				isSorted = true;
			}

			var total = items.Count();
			var result=new QueryData<User>()
			{
				Items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(),
				TotalCount = total,
				IsFiltered = true,
				IsSorted = isSorted,
				IsSearch = true
			};
            return result;
		}
        
        /// <summary>
        /// 新增或编辑用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="changedType"></param>
        /// <returns></returns>
        private async Task<bool> OnSaveAsync(User user, ItemChangedType changedType)
        {
            try
            {
                if (changedType == ItemChangedType.Add)
                {
                    // 新增用户时，密码不能为空，设置默认密码
                    var passwordHash = string.IsNullOrEmpty(user.PasswordHash) ? 
                        $"{Furion.App.GetConfig<string>("SecretKey")}123456" : $"{Furion.App.GetConfig<string>("SecretKey")}{user.PasswordHash}";

                    var createDto = new UserCreateDto(
                        user.UserName,
                        passwordHash,
                        user.DisplayName,
                        user.IsDisabled);

                    var (ok, errorMessage, created) = await UserService.CreateAsync(createDto);
                    if (ok && created is not null)
                    {
                        user.Id = created.Id;
                        LogWrapper.Information($"创建用户[{user.DisplayName}]成功");
                        return true;
                    }
                    else
                    {
                        // 记录错误信息
                        // Log.Error($"创建用户失败: {errorMessage}");
                        LogWrapper.Error($"创建用户失败: {errorMessage}");
                        return false;
                    }
                }
                else
                {
                    // 修改用户时，如果密码为空则保持原密码不变
                    var updateDto = new UserUpdateDto(
                        user.UserName,
                        $"{Furion.App.GetConfig<string>("SecretKey")}{user.PasswordHash}", // 如果为空，服务层应该保持原密码不变
                        user.DisplayName,
                        user.IsDisabled);

                    var (ok, errorMessage, updated) = await UserService.UpdateAsync(user.Id, updateDto);
                    if (!ok)
                    {
                        // Log.Error($"更新用户失败: {errorMessage}");
                        LogWrapper.Error($"更新用户失败: {errorMessage}");
                    }
                    else
                    {
                        LogWrapper.Information($"更新用户信息成功!");
                    }
                    return ok;
                }
            }
            catch (Exception ex)
            {
                LogWrapper.Error($"保存用户时发生异常: {ex.Message}", exception: ex);
                return false;
            }
        }

        private async Task<bool> OnDeleteAsync(IEnumerable<User> rows)
        {
            var ids = rows.Select(x => x.Id).ToList();
            if (ids.Count == 0) return true;

            // 逐个使用业务层删除（也可改为并行或在服务中实现批量删除）
            foreach (var id in ids)
            {
                var (ok, _) = await UserService.DeleteAsync(id);
                if (!ok) return false;
            }
			LogWrapper.Information($"删除用户[{string.Join(',',ids)}]成功");
			return true;
        }

        /// <summary>
        /// 编辑单个用户
        /// </summary>
        /// <param name="user">用户对象</param>
        private void EditItem(User user)
        {
            // 这里可以添加编辑逻辑，比如打开编辑对话框
            // 由于Table组件已经有内置的编辑功能，这里可以留空或添加自定义逻辑
            LogWrapper.Information($"编辑用户: {user.DisplayName}");
        }

        /// <summary>
        /// 删除单个用户
        /// </summary>
        /// <param name="user">用户对象</param>
        private async Task DeleteItem(User user)
        {
            // 确认删除
            if (await JSRuntime!.InvokeAsync<bool>("confirm", $"确定要删除用户 {user.DisplayName} 吗？"))
            {
                var (ok, errorMessage) = await UserService.DeleteAsync(user.Id);
                if (ok)
                {
                    LogWrapper.Information($"删除用户 {user.DisplayName} 成功");
                    // 刷新数据
                    Items = (await UserService.GetAllEntiyAsync()).ToList();
                    EditItems = Items;
                    StateHasChanged();
                }
                else
                {
                    LogWrapper.Error($"删除用户失败: {errorMessage}");
                }
            }
        }
    }
}
